package com.android.fragmentdemo.thread20
import org.junit.Test
import java.util.Random
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock

class Demo20 {
    @Test
    fun testRunnable() {
        val coreCount = Runtime.getRuntime().availableProcessors()
        val pool = ThreadPoolExecutor(coreCount, 20, 1, TimeUnit.SECONDS, LinkedBlockingQueue(15))
        val lock : Lock = ReentrantLock()
        val random = Random()
        val mRunnableList = mutableListOf<Runnable>()
        for (i in 0.until(20)) {
            mRunnableList.add(MyRunnable("客户--${i + 1}", lock, random))
        }
        mRunnableList.shuffle()
        for (runnable in mRunnableList) {
            pool.execute(runnable)
        }
        pool.shutdown()

        Thread.sleep(25 * 1000)
    }

    class MyRunnable(name: String, mLock: Lock, mRandom: Random) : Runnable {

        private val mName = name

        private val lock = mLock

        private val random = mRandom

        override fun run() {
            try {
                lock.lock()

                println("${mName}正在使用${Thread.currentThread().name}参与秒杀任务了......")

                try {
                    Thread.sleep(random.nextInt(2000).toLong())
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }

                if (count > 0) {
                    println("${mName}正在使用${Thread.currentThread().name}秒杀:${count--}号商品啦")
                } else {
                    println("${mName}正在使用${Thread.currentThread().name}秒杀失败了")
                }
            } finally {
                lock.unlock()
            }

//            println("${mName}正在使用${Thread.currentThread().name}参与秒杀任务了......")
//
//            try {
//                Thread.sleep(50L + random.nextInt(2000).toLong())
//            } catch (ex: Exception) {
//                ex.printStackTrace()
//            }
//
//            synchronized(MyRunnable::class.java) {
//                if (atomicInt.get() > 0) {
//                    println("${mName}正在使用${Thread.currentThread().name}秒杀:${atomicInt.get()}号商品啦")
//                    atomicInt.set(atomicInt.get().dec())
//                } else {
//                    println("${mName}正在使用${Thread.currentThread().name}秒杀失败了")
//                }
//            }

        }
    }

    companion object {
        var count = 10

        var atomicInt = AtomicInteger(10)
    }
}